
package com.yicheng.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yicheng.controller.utils.R;
import com.yicheng.domain.Book;
import com.yicheng.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;


//表现层 基于Restful进行表现层接口开发
//使用Postman测试表现层接口功能



@RestController
@RequestMapping("/books")
public class BookController {

    //注入业务层
    @Autowired
    private IBookService bookService;

//    @GetMapping//获取所有图书
//    public R getAll(){
//        return new R(true, bookService.list());
//    }

    @PostMapping//添加图书
    public R save(@RequestBody Book book) throws IOException {
        return new R(bookService.save(book));
    }


    @PutMapping//修改图书
    public R update(@RequestBody Book book){
        return new R(bookService.updateById(book));
    }

    @DeleteMapping("{id}") //删除图书
    public R delete(@PathVariable Integer id){
        return new R(bookService.removeById(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true, bookService.getById(id));
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        IPage<Book> page = bookService.getPage(currentPage, pageSize);
        if(currentPage > page.getPages())
            page = bookService.getPage((int)page.getPages(), pageSize);
        return new R(true, page);
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize, Book book){

        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        IPage<Book> page = bookService.getPage(currentPage, pageSize, book);
        if(currentPage > page.getPages())
            page = bookService.getPage((int)page.getPages(), pageSize, book);
        return new R(true, page);
    }

}

